package edu.hrbu.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * @author 徐登宇
 * @date 2022-10-26 17:54
 */
@WebListener
public class OnlineUserListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        if ("loginUser".equals(event.getName())) {
            ServletContext application = event.getSession().getServletContext();
            Integer onlineUsers = (Integer) application.getAttribute("onlineUsers");
            if (onlineUsers == null) {
                application.setAttribute("onlineUsers", 1);
            } else {
                application.setAttribute("onlineUsers", ++ onlineUsers);
            }
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if ("loginUser".equals(event.getName())) {
            ServletContext application = event.getSession().getServletContext();
            Integer onlineUsers = (Integer) application.getAttribute("onlineUsers");
            application.setAttribute("onlineUsers", --onlineUsers);
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        HttpSessionAttributeListener.super.attributeReplaced(event);
    }
}
